#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <debug.h>
#include <os_api.h>
#include <file_api.h>
#include <cgi/applets.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))


static int autoreboot_post_get(int Action, dc_args_t *dca);
static int autoreboot_post_set(int Action, dc_args_t *dca);

static struct applet_info module_applet_array[]=
{
    {
        .di_modname = "autoreboot",
        .di_version = 1,
        .di_handler_post_get_func = autoreboot_post_get,
        .di_handler_post_set_func = autoreboot_post_set,
    },
};

static int autoreboot_post_get(int Action, dc_args_t *dca)
{
    MrvXMLElement *root = NULL, *pChild = NULL;
    int nIndex = 0;
    char buf[64];
    int mode = 0;
    unsigned time = 0;
    char *psm_str = NULL;

    LOG_PRINTF("%s %d", __func__, Action);
    if (!dca)
        return -1;
    if (dca->dc_type != DUSTER_CB_ARGS_XML)
        return -1;
    root = dca->dc_root;
    if (!root)
        return -1;

    psm_str = psm_get_wrapper("autoreboot", NULL, "mode");
    if (psm_str) {
        mode = atoi(psm_str);
        free(psm_str);
    }
    psm_str = psm_get_wrapper("autoreboot", NULL, "time");
    if (psm_str) {
        time = atoi(psm_str);
        free(psm_str);
    }

    pChild = MrvFindElement(root, "mode");
    if (pChild) {
        for (nIndex = 0; nIndex < pChild->nSize; nIndex++) {
            MrvDeleteNode(&pChild->pEntries[nIndex]);
        }
        if (pChild->pEntries)
            free(pChild->pEntries);
        pChild->pEntries = NULL;
        pChild->nMax = 0;
        pChild->nSize = 0;
        snprintf(buf, sizeof(buf), "%d", mode);
        MrvAddText(pChild, MrvStrdup(buf, 0), 1);
    }
    pChild = MrvFindElement(root, "time");
    if (pChild) {
        for (nIndex = 0; nIndex < pChild->nSize; nIndex++) {
            MrvDeleteNode(&pChild->pEntries[nIndex]);
        }
        if (pChild->pEntries)
            free(pChild->pEntries);
        pChild->pEntries = NULL;
        pChild->nMax = 0;
        pChild->nSize = 0;
        snprintf(buf, sizeof(buf), "%u", time);
        MrvAddText(pChild, MrvStrdup(buf, 0), 1);
    }
    return 0;
}

static int autoreboot_post_set(int Action, dc_args_t *dca)
{
    LOG_PRINTF("%s %d", __func__, Action);
    if (Action == DUSTER_CONFIG_SET) {
        psm_commit__();
    }
    return 0;
}

int main(void)
{
    LOG_PRINTF("Start WebUI");
    web_applet_register(module_applet_array, ARRAY_SIZE(module_applet_array));
    return 0;
}
